﻿
namespace System.Extensions.Windows.Forms.Design
{
  using System;
  using System.ComponentModel;
  using System.Drawing.Design;
  using System.Windows.Forms;
  using System.Windows.Forms.Design;

  internal class WizardPageCollectionEnumEditor : UITypeEditor
  {
    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
    {
      IWindowsFormsEditorService service = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
      if (service == null)
      {
        return value;
      }

      WizardPageCollection pages = (WizardPageCollection)value;
      ListBox box = new ListBox();
      box.Tag = new object[] { context, provider, value };
      box.Dock = DockStyle.Fill;
      box.HorizontalScrollbar = true;
      box.SelectedIndexChanged += new EventHandler(this.Box_SelectedIndexChanged);

      foreach (WizardPage page in pages)
      {
        box.Items.Add(page);
      }

      service.DropDownControl(box);
      return value;
    }

    public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
    {
      return UITypeEditorEditStyle.DropDown;
    }

    private void Box_SelectedIndexChanged(object sender, EventArgs e)
    {
      ListBox box = (ListBox)sender;
      IServiceProvider provider = (IServiceProvider)((object[])box.Tag)[1];
      WizardPageCollection pages = (WizardPageCollection)((object[])box.Tag)[2];
      IWindowsFormsEditorService service = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
      if (service == null)
      {
        return;
      }

      pages.Owner.CurrentPageIndex = box.SelectedIndex;
      service.CloseDropDown();
      box.Dispose();
    }
  }
}
